//
//  LeftOrderPayVC.m
//  Ufan
//
//  Created by yangqingluo on 15/12/15.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "LeftOrderPayVC.h"
#import "OrderNameCell.h"
#import "PayStyleCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import "SHXMLParser.h"
#import "DataSigner.h"
#import "WXApi.h"

@interface LeftOrderPayVC ()<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>{
    BOOL recordResults;
}

@property (nonatomic, strong) NSXMLParser *xmlParser;
@property (nonatomic, retain) NSMutableDictionary *soapDictionary;
@property (nonatomic, retain) NSString *tag;

@property (nonatomic, strong) UFOrderInfo *order;
@property (nonatomic, strong) UITableView *showTableView;

@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) UILabel *bottomPriceLabel;

@property (nonatomic, strong) NSArray *payStyleArray;

@end

@implementation LeftOrderPayVC

- (instancetype)initWithOrder:(UFOrderInfo *)order{
    self = [super init];
    if (self) {
        self.order = order;
    }
    
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.showTableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupBarButtonItem];
    [self.view addSubview:self.bottomBar];
}

- (void)setupBarButtonItem{
    self.title = @"确认订单";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(isGoBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}

- (void)isGoBack{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"是否放弃付款？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        if (self.payInfo) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else{
            [self goBack];
        }
    }
    
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)payNow{
    if ([AppPublic shareInstanceApp].payStyleSelected) {
        //支付宝
        if ([[AppPublic shareInstanceApp].payStyleSelected.idString isEqualToString:@"001"]) {
            if (self.payInfo) {
                [self showHudInView:self.view hint:@"获取支付信息..."];
                [QKHttpManager payOrder:nil paymentID:self.payInfo.tradeNO payStyleID:[AppPublic shareInstanceApp].payStyleSelected.idString completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    [self showHint:httpRespString(error, object)];
                    if ([object isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *respDic = (NSDictionary *)object;
                        if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                            
                            [[AppPublic shareInstanceApp]parseWithString:respDic[@"formString"]];
                            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[AppPublic shareInstanceApp].parseDic];
                            
                            
                            
                            [self doAlipay:dic];
                        }
                    }
                }];
            }
            else{
                
                [self showHudInView:self.view hint:@"获取支付信息..."];
                [QKHttpManager payOrder:self.order.idString paymentID:nil payStyleID:[AppPublic shareInstanceApp].payStyleSelected.idString completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    [self showHint:httpRespString(error, object)];
                    if ([object isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *respDic = (NSDictionary *)object;
                        if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                            
                            [[AppPublic shareInstanceApp]parseWithString:respDic[@"formString"]];
                            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[AppPublic shareInstanceApp].parseDic];
                            
                            
                            
                            [self doAlipay:dic];
                        }
                    }
                }];
            }

        }
        
        else if ([[AppPublic shareInstanceApp].payStyleSelected.idString isEqualToString:@"002"]){
            //微信支付
            
            if (self.payInfo) {
                [self showHudInView:self.view hint:@"获取支付信息..."];
                [QKHttpManager payOrder:nil paymentID:self.payInfo.tradeNO payStyleID:[AppPublic shareInstanceApp].payStyleSelected.idString completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    [self showHint:httpRespString(error, object)];
                    [self hideHud];
                    [self showHint:httpRespString(error, object)];
                    if ([object isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *respDic = (NSDictionary *)object;
                        if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                            NSDictionary *prepay = respDic[@"prepay"];
                            [self doWXPay:prepay];
                        }
                    }
                }];
            }
            else{
                
                [self showHudInView:self.view hint:@"获取支付信息..."];
                [QKHttpManager payOrder:self.order.idString paymentID:nil payStyleID:[AppPublic shareInstanceApp].payStyleSelected.idString completion:^(NSObject *object, NSError *error){
                    [self hideHud];
                    [self showHint:httpRespString(error, object)];
                    if ([object isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *respDic = (NSDictionary *)object;
                        if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                            NSDictionary *prepay = respDic[@"prepay"];
                            [self doWXPay:prepay];
                        }
                    }
                }];
            }
        }
        else{
            [self showHint:@"暂时不支持该支付方式"];
        }
    }
    else{
        [self showHint:@"请选择支付方式"];
    }
    
    
}

- (void)doWXPay:(NSDictionary *)prepay{
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    
    req.partnerId           = prepay[@"partnerid"];
    req.prepayId            = prepay[@"prepayid"];
    req.nonceStr            = prepay[@"noncestr"];
    req.timeStamp           = [prepay[@"timestamp"] intValue];
    req.package             = prepay[@"package"];
    req.sign                = prepay[@"paySign"];
    [WXApi sendReq:req];
    
    if (self.payInfo) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else{
        [AppPublic shareInstanceApp].needRefreshOrderList = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)doAlipay:(NSDictionary *)dic{
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    NSString *partner = dic[@"partner"];
    NSString *seller = dic[@"seller_id"];
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = dic[@"out_trade_no"];
    if (self.order.productItems.count) {
        UFProductItem *item = self.order.productItems[0];
        
        order.productName = item.productName;
        order.productDescription = item.itemName;
    }
    
    order.amount = [NSString stringWithFormat:@"%.2f",self.order.totalPrice]; //商品价格
    order.notifyURL =  dic[@"notify_url"];
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"1d";
    order.showUrl = dic[@"show_url"];
    
    NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMgojbH7OZNQ41pm/jgvWXZBhyNWhf3hjWbhl43X05qz0WyiWij7QjJ80iQjotFd7XjuQWUcGl9MpXcYEjjZiP7/5283qlGPJUNg/UUDLA6dG9L15JkzUnYPV1+vTgw/bjSsj4Hh+P8hu/FdV/bIItQCT7o1eapgx+N7aPj8UxdvAgMBAAECgYBtWAogQtfvLG8nQcB7PRKoUZ/bpDbKvN8cZvz+FfuZNcagjAio/qnpHttFttoJekByoeXDsJiPmzWBW/sIZ344qEDgo05IOa9VjgJIu/uQEGklyszS90TGYITY9qcxZUA+4BjiLx5WERfu/nOHRyKFqCWLQ/YD1Gr6DE49x8r3wQJBAO3CkfRDUVvwILZGf5ciVkTDRbanieZTAJwe6w3qZKkfXo1HCJVG7/Pmhudulw+3g7wsOHXxQ3FKjpxrdSodmb8CQQDXg4Pz9/yGYnXYb1yQ6vVlTuIF4zksTtTI5xKv8kqOh+Vg+AAzItsruz6gKr7CX8C3jOTp+6PaqWdLtBf2sw5RAkAlA+SrLYvOD21YU1Nr2RmrLOd+j0jFxehTZfDcQsCXH94dipCIhPm4dAxOnYYBGWX19sB3hC8mxR+8tHISM3eLAkAAz+8UYU/jVcWp7imEJk6MdjKl4QhbIWTt6OkKHrinNt3ncqfViYEX9hmzUtXrN58rUe2e8CLa9R59i403kc8xAkEAnwKg9vYEJs8/o+i2C8I9vrNra6gOq0x/i7be0k/EYJazCQuOhUqp+/euPkW+0v/chDE6wi54GYsiQ6p6sM99hw==";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"Ufan";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            
            if (resultDic[@"memo"]) {
                NSString *memo = [NSString stringWithFormat:@"%@",resultDic[@"memo"]];
                if (memo.length) {
                    [self.navigationController.view makeToast:memo duration:QKToastDuration position:QKToastPoint];
                }
                
            }
            
            if ([resultDic[@"resultStatus"] intValue] == 6001 || [resultDic[@"resultStatus"] intValue] == 9000) {
                
                if (self.payInfo) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                else{
                    [AppPublic shareInstanceApp].needRefreshOrderList = YES;
                    [self.navigationController popViewControllerAnimated:YES];
                }
                
            }
            
            
            
        }];
    }
}

#pragma mark
#pragma NSXMLParserDelegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict{
    
        NSLog(@"4 parser didStarElemen:%@ namespaceURI:%@ qualifiedName:%@ attributes:%@",elementName,namespaceURI,qName,attributeDict);
    

    
    self.tag=elementName;
    recordResults = YES;

}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    
    NSLog(@"5 parser: foundCharacters:%@",string);
    if( recordResults ){
        [self.soapDictionary setObject:string forKey:self.tag];
    }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
        NSLog(@"6 parser didEndElemen:%@ namespaceURI:%@ qualifiedName:%@",elementName,namespaceURI,qName);
    
    recordResults = FALSE;
    
        NSLog(@"parse result is %@",self.soapDictionary);
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
    	NSLog(@"-------------------start--------------");
}

- (void)parserDidEndDocument:(NSXMLParser *)parser{
    	NSLog(@"-------------------end--------------");
    //    if(soapResults.length)soapResults=(NSMutableString *)[soapResults substringToIndex:soapResults.length-1];
    //	NSLog(@"soapResults is %@\n%@\n%@",soapResults,soapArray,soapDictionary);
    //    NSLog(@"the response is %@",soapDictionary);
}
//报告不可恢复的解析错误
- (void)paser:parserErrorOccured{
    NSLog(@"-------------------error--------------");
}

#pragma getter
- (NSArray *)payStyleArray{
    if (!_payStyleArray) {
        _payStyleArray = @[payStyleMake(@"001", @"支付宝", @"pay_alipay", YES),payStyleMake(@"002", @"微信支付", @"weixin", NO),];
//        _payStyleArray = @[payStyleMake(@"001", @"支付宝", @"pay_alipay", YES)];
    }
    
    return _payStyleArray;
}

- (UITableView *)showTableView{
    if (!_showTableView) {
        _showTableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStylePlain];
        _showTableView.multipleTouchEnabled = YES;
        _showTableView.dataSource = self;
        _showTableView.delegate = self;
        _showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_showTableView setBackgroundColor:[UIColor clearColor]];
        
        [self.view insertSubview:_showTableView belowSubview:self.bottomBar];
    }
    
    return _showTableView;
}

- (UIView *)bottomBar{
    if (!_bottomBar) {
        _bottomBar = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - TAB_BAR_HEIGHT -STATUS_BAR_HEIGHT, self.view.width, TAB_BAR_HEIGHT)];
        _bottomBar.backgroundColor = [UIColor whiteColor];
        _bottomBar.layer.shadowColor = [UIColor blackColor].CGColor;
        _bottomBar.layer.shadowOffset = CGSizeMake(0, -1);
        _bottomBar.layer.shadowOpacity = 0.2;
        
        UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        buyButton.frame = CGRectMake(0, 0, 100, 36);
        buyButton.center = CGPointMake(_bottomBar.width - 0.5 * buyButton.width - 10, 0.5 * _bottomBar.height);
        buyButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [buyButton setBackgroundColor:[UIColor orangeColor]];
        buyButton.layer.cornerRadius = 5;
        buyButton.layer.masksToBounds = YES;
        [buyButton setTitle:@"立即支付" forState:UIControlStateNormal];
        [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buyButton addTarget:self action:@selector(payNow) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBar addSubview:buyButton];
        
        self.bottomPriceLabel.center = CGPointMake(buyButton.left - 0.5 * self.bottomPriceLabel.width - 10, 0.5 * _bottomBar.height);
        [_bottomBar addSubview:self.bottomPriceLabel];
    }
    
    return _bottomBar;
}

- (UILabel *)bottomPriceLabel{
    if (!_bottomPriceLabel) {
        _bottomPriceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
        _bottomPriceLabel.textColor = [UIColor orangeColor];
        _bottomPriceLabel.font = [UIFont systemFontOfSize:14.0];
        _bottomPriceLabel.textAlignment = NSTextAlignmentRight;
        _bottomPriceLabel.text = [NSString stringWithFormat:@"合计：%.2f 元",self.order.totalPrice];
    }
    
    return _bottomPriceLabel;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:{
            return 2;
        }
            break;
            
        case 1:{
            return 1 + self.payStyleArray.count;
        }
            break;
            
        default:{
            return 0;
        }
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *CellIdentifier_ordertitle = @"CellIdentifier_ordertitle";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier_ordertitle];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier_ordertitle];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UIView *_bottomLineView1 = [[UIView alloc] initWithFrame:CGRectMake(15, 59, tableView.width - 30, 1)];
            _bottomLineView1.backgroundColor = UFCOLOR_GRAYLINE;
            [cell.contentView addSubview:_bottomLineView1];
        }
        
        switch (indexPath.row) {
            case 0:{
                cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
                cell.textLabel.textColor = [UIColor blackColor];
                cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0];
                cell.detailTextLabel.textColor = [UIColor blackColor];
                
                if (self.payInfo) {
                    cell.textLabel.text = self.payInfo.productName;
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f元 × %d",self.payInfo.itemPrice,self.payInfo.quantity];
                }
                
                else if (self.order.productItems.count) {
                    UFProductItem *item = self.order.productItems[0];
                    
                    cell.textLabel.text = item.productName;
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f元 × %d",item.itemPrice,item.quantity];
                    
                }
                
            }
                break;
                
            case 1:{
                cell.textLabel.font = [UIFont systemFontOfSize:12.0];
                cell.textLabel.textColor = [UIColor lightGrayColor];
                cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:14.0];
                cell.detailTextLabel.textColor = [UIColor blackColor];
                
                if (self.payInfo) {
                    cell.textLabel.text = [NSString stringWithFormat:@"共%d件",self.payInfo.quantity];
                }
                else if (self.order.productItems.count) {
                    UFProductItem *item = self.order.productItems[0];
                    
                    cell.textLabel.text = [NSString stringWithFormat:@"共%d件",item.quantity];
                }
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"合计：%.2f元",self.order.totalPrice];
            }
                break;
                
            default:
                break;
        }
        
        return cell;
    }
    else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            NSString *CellIdentifier = @"OrderNameCell";
            OrderNameCell *cell = (OrderNameCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if (cell == nil) {
                cell = [[OrderNameCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            cell.name = @"选择支付方式";
            
            
            return cell;
        }
        else{
            NSString *CellIdentifier = @"PayStyleCell";
            PayStyleCell *cell = (PayStyleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if (cell == nil) {
                cell = [[PayStyleCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            cell.payStyle = self.payStyleArray[indexPath.row - 1];
            
            return cell;
            
            
        }
    }
    
    return [UITableViewCell new];
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 60;
    }
    else if (indexPath.section == 1){
        if (indexPath.row == 0) {
//            return [OrderNameCell tableView:tableView heightForRowAtIndexPath:indexPath];
            return 80;
        }
        else{
            return [PayStyleCell tableView:tableView heightForRowAtIndexPath:indexPath];
        }
    }
    
    
    return 44;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        if (indexPath.row == 0) {
            
        }
        else{
            [AppPublic shareInstanceApp].payStyleSelected = self.payStyleArray[indexPath.row - 1];
            [tableView reloadData];
        }
    }
}

@end
